/*
 * Copyright 2009 Andreas Borglin andreas.borglin@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package borge.mobile.app.jakoon;

import javax.microedition.rms.RecordStore;

/**
 * Class that handles all communication with RMS
 * @author Andreas Borglin
 */
public class RMSHandler {

    private static final String DEFAULT_PATH_RS = "DefaultPath";

    public RMSHandler(){

    }

    private static byte[] getData(RecordStore rs, int index){

        byte[] data = null;
        try{
            data = rs.getRecord(index);
        }
        catch(Exception e){
            // ignore
        }

        return data;

    }

    public static void setDefaultPath(String path){

        try{
            RecordStore rs = RecordStore.openRecordStore(DEFAULT_PATH_RS, true);
            byte[] data = getData(rs, 1);

            byte[] strData = path.getBytes();
            if(data == null){
                int id = rs.addRecord(strData, 0, strData.length);
            }
            else{
                rs.setRecord(1, strData, 0, strData.length);
            }

            rs.closeRecordStore();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public static String getDefaultPath(){
        try{
            RecordStore rs = RecordStore.openRecordStore(DEFAULT_PATH_RS, true);
            byte[] data = getData(rs, 1);

            if(data == null)
                return null;

            rs.closeRecordStore();
            return new String(data);
        }
        catch(Exception e){
            e.printStackTrace();
        }

        return null;
    }
    
}
